import { defineStore } from 'pinia'
import requestList from '@/service/request'
import { getItem, removeItem, setItem } from '@/utils/local';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
const router = useRouter()
//token
export const useAuthStore = defineStore('auth',()=>{
  const myToken = ref('')
  const refreshToken = ref('')

  myToken.value = getItem('token') || ''

  const login = async (postData:any)=>{
    const res = await requestList.loginApi(postData)
    if(res.code === 1){
      const {token} = (res.data as any)
      setItem('token',token)
      myToken.value = token
      // router.push('/index')
      window.$message.success('登录成功')
    }
  }
  const logout = ()=>{
    removeItem('token')
    myToken.value = ''
  }

  const reToken = async (postData:any)=>{
    const res = await requestList.refreshTokenApi(postData)
    if(res.code === 1){
      const {token,refreshToken} = (res.data as any)
      setItem('token',token)
      myToken.value = token
      refreshToken.value = refreshToken
    }
  }

  return {
    myToken,refreshToken,login,logout,reToken
  }
})

// 用户信息
export const useUserInfoStore = defineStore('userInfo',()=>{
  const userInfo = ref({})
  const getUserInfo = async () => {
    const res = await requestList.userInfoApi()
    if(res.code === 1){
      setItem('curUserInfo',res.data)
      userInfo.value = getItem('curUserInfo')
    }
  }

  return {
    userInfo,getUserInfo
  }
})
